<?php
namespace app\admin\library;

use support\Request;
use support\View;

trait Crud
{
    public function index(Request $request)
    {
        if ($request->expectsJson()) {
            $list = $this->model::search($request->get('search'))->orderByDesc('created_at')->forPage($request->get('page', 1))->get();
            $count = $this->model::query()->count();
            $this->success("获取成功", [
                'list' => $list,
                'total' => $count
            ]);
        }
        return $this->view('index');
    }

    public function show(Request $request)
    {
        $id = $request->get('id', null);
        if ($id !== null) {
            $row = $this->model::query()->find($id);
            View::assign('row', $row);
        }

        return $this->view('show');
    }

    public function add(Request $request) {
        $this->store($request);
    }

    public function edit(Request $request) {
        $this->store($request);
    }

    protected function store(Request $request)
    {
        $form = $request->post('form');
        if (isset($form['id'])) {
            $row = $this->model::query()->where('id', $form['id'])->first();
            if (!$row) {
                $this->error('未找到!');
            }
            unset($form['id']);
        }else {
            $row = new $this->model();
        }
        $row->fill($form);
        $row->save();
        $this->success("操作成功!");
    }

    public function del(Request $request) {
        $list = $this->model::query()->whereIn('id', $request->post('ids'))->get();
        $list->each(function ($v) {
            $v->delete();
        });
        $this->success("操作成功!");
    }
}
